conecta_mysql;
%conecta_sqlserver;
mysqlquery = 'SELECT Simid,Maxtime,Pdb4, Temp, Run FROM simulacao WHERE Temp = 498 and Maxtime > 70800 and Maxtime <=71000 and Pdb4 in (SELECT Pdb4 FROM simulacao WHERE Temp =498 GROUP BY Pdb4 HAVING count(Run) >= 2)';
curs = exec(mysql, mysqlquery);
sim_id=fetch(curs);


sims = sim_id.Data(:,1);
maxtimes = sim_id.Data(:,2);

for s = 1:size(sims,1)
    sim = sims{s};
    maxtime = maxtimes{s};
    intervalo = 0:5000:maxtime;
    intervalo = [intervalo maxtime];
    for i = intervalo
        sqlserverquery = ['SELECT c.atom_number, i.atom_name, i.residue, i.chain_id, i.residue_number, i.icode, c.x_coord, c.z_coord, c.y_coord, i.atom_type, i.main_chain, c.sim_id FROM dbo.[Coord_' num2str(sim) '] AS c JOIN dbo.ID AS i ON ( i.struct_id = c.struct_id and i.atom_number = c.atom_number ) WHERE step=' num2str(i) ' ORDER BY atom_number '];
   %     curs = exec(sqlserver, sqlserverquery);
   %     dados=fetch(curs);
   %     colunas = {'atom_number' 'atom_name' 'residue' 'chain_id' 'residue_number' 'icode' 'x_coord' 'z_coord' 'y_coord' 'atom_type' 'main_chain' 'sim_id'};
   %     fastinsert(mysql, 'pdb', colunas, dados.Data);
    end
end
% SELECT `Pdb4`, count(Run) from simulacao group by `Pdb4` having count(Run)>= 2
%SELECT Simid,Maxtime,Pdb4, Temp, Run FROM `simulacao` WHERE Temp = 498 and Maxtime >= 50000 and Pdb4 in (SELECT `Pdb4` FROM simulacao WHERE Temp =498 GROUP BY `Pdb4` HAVING count( Run ) >=2)
%SELECT Simid,Maxtime,Pdb4, Temp, Run FROM simulacao WHERE Temp = 498 and Maxtime >= 70000 and Maxtime <=71000 and Pdb4 in (SELECT Pdb4 FROM simulacao WHERE Temp =498 GROUP BY Pdb4 HAVING count(Run) >= 2)
%SELECT 'ATOM', c.atom_number, i.atom_name, i.residue, i.residue_number, c.x_coord, c.z_coord, c.y_coord, c.sim_id, step FROM dbo.[Coord_678] AS c JOIN dbo.ID AS i ON ( i.struct_id = c.struct_id and i.atom_number = c.atom_number ) WHERE step%10000000=0 ORDER BY step, atom_number